const vm = require('vm')
const util = require('util')

let fn = async (cmd, {db, reg}, topic) => {
    try {
        let start = new Date()
        let script = new vm.Script(cmd)
        let context = new vm.createContext({db, reg})
        script.runInContext(context)
        let result = context.r
        let during = new Date() - start
        return {
            sender: {name: 'eval'},
            data: {
                result,
                during,
                cmd
            }
        }
    } catch (e) {
        return {
            topic,
            data: e.message
        }
    }

}

fn.type = 'peer'

module.exports = fn